package com.boot.shiro.controller;

import com.boot.shiro.entity.SysUserEntity;
import com.boot.shiro.result.CodeMsg;
import com.boot.shiro.result.Result;
import com.boot.shiro.service.SysUserService;
import com.boot.shiro.util.PageUtils;
import com.boot.shiro.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController{
	@Autowired
	private SysUserService sysUserService;

	/**
	 * 获取登录的用户信息
	 */
	@RequestMapping("/info")
	public Result info(){
		SysUserEntity user = ShiroUtils.getUserEntity();
		Map r = new HashMap<String, Object>();
		r.put("user", user);
		return Result.success(r);
	}

	/**
	 * 修改登录用户密码
	 */
	@RequestMapping("/password")
	public Result password(String password, String newPassword){
		//Assert.isBlank(newPassword, "新密码不为能空");
		SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
		//原密码
		password = ShiroUtils.sha256(password, user.getSalt());
		//新密码
		newPassword = ShiroUtils.sha256(newPassword, user.getSalt());

		//更新密码
		boolean flag = sysUserService.updatePassword(user.getUserId(), password, newPassword);
		if(!flag){
			return Result.error(CodeMsg.PASSWORD_ERROR);
		}
		return Result.success(null);
	}

	/**
	 * 所有用户列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:user:list")
	public Result list(@RequestParam Map<String, Object> params){
		PageUtils page = sysUserService.queryPage(params);
		Map r = new HashMap<String, Object>();
		r.put("page", page);
		return Result.success(r);
	}

	/**
	 * 用户信息
	 */
	@RequestMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public Result info(@PathVariable("userId") Long userId){
		SysUserEntity user = sysUserService.getById(userId);

		//获取用户所属的角色列表
		//List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		//user.setRoleIdList(null);

		Map r = new HashMap<String, Object>();
		r.put("user", user);
		return Result.success(r);
	}
}
